package com.graduate.emos.wx.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//全局异常处理器
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//响应500状态码
    @ExceptionHandler(Exception.class) //该注解捕获异常
    public String validExceptionHandler(Exception e){
        log.error("执行异常",e);
        if (e instanceof MethodArgumentNotValidException){
            //如果该异常为方法参数异常
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            //将错误信息返回到前端
            return exception.getBindingResult().getFieldError().getDefaultMessage();
        }else if (e instanceof EmosException){
            //该异常为自定义异常
            EmosException exception = (EmosException) e;
            return exception.getMsg();
        }else if (e instanceof UnauthorizedException){
            //未授权异常
            return "你不具备相关权限！";
        }else{
            return "后端系统执行异常！";
        }
    }
}
